package com.hongkuncheng.cms.controller.admin;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.Webinfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 模板文件管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/templatefile")
public class AtemplatefileController extends BaseController {

    // 文件列表
    @RequestMapping
    public String index() throws Exception {
        webinfo = factorySession.get(Webinfo.class, 1);
        request.setAttribute("webinfo", webinfo);
        String currentdir = request.getParameter("currentdir").replace("\\", "/");
        if (currentdir.equals(applicationDirectory + "/template")) {
            response.sendRedirect("../template/");
            return null;
        }
        request.setAttribute("currentdir", currentdir);
        request.setAttribute("currentdirpath", currentdir.replace(applicationDirectory
                .replace("\\", "/"), ""));
        request.setAttribute("parentdir", currentdir.substring(0, currentdir.lastIndexOf("/")));
        List<File> templatedirs = FileHelper.getDirectorys(currentdir);
        List<File> templatefiles = FileHelper.getFiles(currentdir);
        String templatefilenames = null;
        for (File file : templatefiles) templatefilenames += "," + file.getName();
        if (templatefilenames != null) templatefilenames = templatefilenames.substring(1);
        request.setAttribute("templatefilenames", templatefilenames);
        request.setAttribute("templatedirs", templatedirs);
        request.setAttribute("templatefiles", templatefiles);
        return view();
    }

    // 文件编辑
    @RequestMapping("fileedit")
    public String fileedit() {
        String currentdir = request.getParameter("currentdir").replace("\\", "/");
        request.setAttribute("currentdir", currentdir);
        String filename = request.getParameter("filename");
        request.setAttribute("filename", filename);
        request.setAttribute("filecontent", FileHelper.Read(currentdir + "/" + filename));
        return view(false);
    }

    // 文件编辑处理
    @RequestMapping("fileeditdo")
    @ResponseBody
    public void fileeditdo() throws UnsupportedEncodingException {
        checkAdminPermission("yunwei_webmaintain_template");
        String name = request.getParameter("name");
        String oldname = request.getParameter("oldname");
        String currentdir = request.getParameter("currentdir").replace("\\", "/");
        String filepath = currentdir + "/" + name;
        if (!name.equals(oldname) && FileHelper.Exists(filepath)) {
            PageHelper.alertAndGoBack("该文件名已存在，请重新输入");
            return;
        }
        String filecontent = request.getParameter("filecontent");
        if (!FileHelper.Exists(filepath) || !filecontent.equals(FileHelper.Read(filepath)))
            FileHelper.write(filepath, filecontent);
        if (!oldname.isEmpty() && !name.equals(oldname)) FileHelper.delete(currentdir + "/" + oldname);
        PageHelper.alertAndRedirect("保存成功", "./?currentdir=" + URLEncoder.encode(currentdir, "UTF-8"));
    }

    // 文件夹编辑
    @RequestMapping("directoryedit")
    public String directoryedit() {
        String currentdir = request.getParameter("currentdir").replace("\\", "/");
        request.setAttribute("currentdir", currentdir);
        String dirname = request.getParameter("dirname");
        request.setAttribute("dirname", dirname);
        return view();
    }

    // 文件夹编辑处理
    @RequestMapping("directoryeditdo")
    @ResponseBody
    public void directoryeditdo() throws Exception {
        checkAdminPermission("yunwei_webmaintain_template");
        String name = request.getParameter("name");
        String currentdir = request.getParameter("currentdir").replace("\\", "/");
        String newFilePath = currentdir + "/" + name;
        File newFile = new File(newFilePath);
        if (newFile.exists()) {
            PageHelper.alertAndGoBack("该文件夹名已存在，请重新输入");
            return;
        }
        String oldName = request.getParameter("oldname");
        if (oldName == "") {
            // 新建
            newFile.mkdir();
        } else {
            // 更新
            String oldFilePath = currentdir + "/" + oldName;
            File oldFile = new File(oldFilePath);
            oldFile.renameTo(newFile);
        }
        PageHelper.alertAndRedirect("保存成功", "./?currentdir=" + URLEncoder.encode(currentdir, "UTF-8"));
    }

    // 模板文件（夹）删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() throws UnsupportedEncodingException {
        checkAdminPermission("yunwei_webmaintain_template");
        String name = request.getParameter("name");
        String currentdir = request.getParameter("currentdir").replace("\\", "/");
        String filePath = currentdir + "/" + name;
        if (name.indexOf(".") > 0) FileHelper.delete(filePath);
        else FileHelper.deleteDir(filePath);
        PageHelper.alertAndRedirect("删除成功", "./?currentdir=" + URLEncoder.encode(currentdir, "UTF-8"));
    }

}
